#!/usr/bin/env node
/**
 * 批量替换前端代码中的console调用为标准化日志
 */

const fs = require('fs')
const path = require('path')
const glob = require('glob')

// 日志映射规则
const LOG_MAPPINGS = {
  'console.log': 'logger.info',
  'console.info': 'logger.info', 
  'console.warn': 'logger.warn',
  'console.error': 'logger.error',
  'console.debug': 'logger.debug'
}

// 获取合适的日志器名称
function getLoggerName(filePath) {
  if (filePath.includes('/stores/')) return 'storeLogger'
  if (filePath.includes('/components/')) return 'componentLogger'
  if (filePath.includes('/views/')) return 'componentLogger'
  if (filePath.includes('/utils/')) return 'logger'
  if (filePath.includes('/router/')) return 'routerLogger'
  return 'logger'
}

// 获取需要导入的日志器
function getImportStatement(filePath) {
  const loggerName = getLoggerName(filePath)
  return `import { ${loggerName} } from '@/utils/logger'`
}

// 处理单个文件
function processFile(filePath) {
  try {
    let content = fs.readFileSync(filePath, 'utf-8')
    let modified = false
    const loggerName = getLoggerName(filePath)
    
    // 检查是否有console调用
    const hasConsole = /console\.(log|info|warn|error|debug)/.test(content)
    if (!hasConsole) {
      return false
    }
    
    console.log(`Processing: ${filePath}`)
    
    // 添加logger导入（如果还没有）
    const hasLoggerImport = content.includes('@/utils/logger')
    if (!hasLoggerImport) {
      const importStatement = getImportStatement(filePath)
      
      // 查找最后一个import语句的位置
      const importRegex = /import\s+.*?from\s+['"][^'"]+['"](\s*\n)?/g
      const imports = content.match(importRegex) || []
      
      if (imports.length > 0) {
        const lastImport = imports[imports.length - 1]
        const lastImportIndex = content.lastIndexOf(lastImport)
        const insertPosition = lastImportIndex + lastImport.length
        
        content = content.slice(0, insertPosition) + importStatement + '\n' + content.slice(insertPosition)
        modified = true
      } else {
        // 如果没有import语句，在文件开头添加
        content = importStatement + '\n\n' + content
        modified = true
      }
    }
    
    // 替换console调用
    Object.entries(LOG_MAPPINGS).forEach(([consoleCall, loggerCall]) => {
      const regex = new RegExp(consoleCall.replace('.', '\\.'), 'g')
      const newContent = content.replace(regex, `${loggerName}.${loggerCall.split('.')[1]}`)
      if (newContent !== content) {
        content = newContent
        modified = true
      }
    })
    
    // 保存文件
    if (modified) {
      fs.writeFileSync(filePath, content, 'utf-8')
      console.log(`  ✅ Updated: ${filePath}`)
      return true
    }
    
    return false
  } catch (error) {
    console.error(`❌ Error processing ${filePath}:`, error.message)
    return false
  }
}

// 主函数
function main() {
  console.log('🚀 Starting console.log replacement...')
  
  const srcDir = path.join(__dirname, 'src')
  const patterns = [
    'src/**/*.vue',
    'src/**/*.js',
    '!src/utils/logger.js',
    '!src/utils/logConfig.js'
  ]
  
  let totalFiles = 0
  let modifiedFiles = 0
  
  patterns.forEach(pattern => {
    const files = glob.sync(pattern, { cwd: __dirname })
    
    files.forEach(file => {
      totalFiles++
      const filePath = path.join(__dirname, file)
      if (processFile(filePath)) {
        modifiedFiles++
      }
    })
  })
  
  console.log('\n📊 Summary:')
  console.log(`Total files processed: ${totalFiles}`)
  console.log(`Files modified: ${modifiedFiles}`)
  console.log(`Files unchanged: ${totalFiles - modifiedFiles}`)
  
  if (modifiedFiles > 0) {
    console.log('\n✅ Console.log replacement completed successfully!')
    console.log('💡 Please review the changes and test the application.')
  } else {
    console.log('\n✨ No console.log statements found to replace.')
  }
}

// 运行脚本
if (require.main === module) {
  main()
}

module.exports = { processFile, getLoggerName }

